package cn.ante.system.service.impl;

import cn.ante.basic.query.BaseQuery;
import cn.ante.basic.utils.PageList;
import cn.ante.org.domain.Department;
import cn.ante.system.domain.Menu;
import cn.ante.system.mapper.MenuMapper;
import cn.ante.system.service.IMenuService;
import cn.ante.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Nai
 * @since 2022-07-11
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> tree() {
        // 先查询所有，将查询出来的所有列表将id作为key,每个对象作为value存储在map中
        List<Menu> menus = menuMapper.loadAll();
        Map<Long, Menu> hashMap = new HashMap<>();
        for (Menu m:menus) {
            hashMap.put(m.getId(),m);
        }

        // new一个部门书集合
        List<Menu> tree = new ArrayList<>();

        // 遍历所有的菜单
        for (Menu menuTmp:menus) {
            // 当parentid为空的时候，就表示是父类，将父类存在临时的map中
            if (menuTmp.getParentId() == null){
                tree.add(menuTmp);
            }else{
                // 不为空就表示他是子类，先找到他的父类，然后加到父类下面
                Menu menu = hashMap.get(menuTmp.getParentId());
                if (menu != null){
                    menu.getChildren().add(menuTmp);
                }
            }
        }

        return tree;
    }

    @Override
    public PageList<Menu> findAll(BaseQuery baseQuery) {
        Integer total = menuMapper.pageCount(baseQuery);
        List<Menu> rows = menuMapper.findAll(baseQuery);
        for (Menu m : rows) {
            Long parentId = m.getParentId();
            Menu menu = menuMapper.loadById(parentId);
                if (menu != null) {
                    m.setParent(menu);
            }
        }
        return new PageList<>(total,rows);
    }

    @Override
    public void add(Menu menu) {
        super.add(menu);
    }

    @Override
    public void update(Menu menu) {
        super.update(menu);
    }

    @Override
    public void remove(Long id) {
        super.remove(id);
    }
}
